<?php
##############################################################################################
#	Compress URL (http://code.google.com/p/compressurl)
#	Author : Abhishek Verma (vermaabhishekp@gmail.com)
#	
#	This file is part of Compress URL.
#	
#	Compress URL is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	Compress URL is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with Compress URL.  If not, see <http://www.gnu.org/licenses/>.
#	
#	compress_url_auth.php : 
#	
#		Renders login form and manages cookie, server and http based authentications
##############################################################################################

// The scrict which includes this file and where all the forms will post to
$thisscript = "add";

// $action = logout logs the user out
$action = "";

// GET action
if ( isset ( $_GET['action'] ) ) $action = $_GET['action'];

function renderForm() {
// Renders the login form for cookie or session based authentication
	global $thisscript;
	echo "<h1><a class='title' href='http://code.google.com/p/compressurl'>Compress URL</a></h1>
	<form name=authForm method=post action=$thisscript>
		<table border=0 cellspacing=0 cellpadding=10>
		<tr>
			<th>Username:</th>
			<td><input type=text name=username value=\"";
			// set username in the text input from the previous post
			if(isset($_POST['username'])) echo $_POST["username"];
			echo "\">
			</td>
		</tr>
		<tr>
			<th>Password:</th>
			<td><input type=password name=password></td>
		</tr>";
		// Authentication must have failed, or else user would have been redirected away
		if ( isset ( $_POST["username"] ) ) {
			echo "
			<tr>
				<td colspan='2'>
					<div style='width: 100%;background:#FFEBE8; padding:5px; text-align:center; font-weight:bold; 
					border: solid 1px #DD3C10; '>
						Authentication failed
					</div>
				</td>
			</tr>";
		}
	echo "<tr>
					<th>&nbsp;</th>
					<td>
						<center>
							<input type=submit value=\"Login\">
						</center>
					</td>
				</tr>
			</table>
		</form>";
	// select the username by default on loading. User probably got it wrong
	echo "<script language=javascript>
					document.authForm.username.select();
					document.authForm.username.focus();
				</script>";
	// A little bragging
	echo "<div id='footer'>
				<table style='width:100%'>
					<tr>
						<td align='left'>
							<a href='http://www.gnu.org/licenses/lgpl.html' style='border:none; text-decoration:none;'>
								<img src='compress_url_libs/gplv3.png' height='31' style='border:none;'>
							</a>
						</td>
						<td align='right'>
							<i>Developed by <a href='mailto:vermaabhishekp@gmail.com'>Abhishek Verma</a></i>
						</td>
					</tr>
				</table>
			</div>";
		exit;
}

// Session based authentication
if ( $authmethod == "session" ) {
	session_start();
	
	if (!session_is_registered("USER")) {
		if ( isset($_POST["username"])
					&& isset($_POST["password"])
					&& ($username == $_POST["username"])
					&& ($password == $_POST["password"])
				) {
			// Valid user
			session_register("USER");
			$_SESSION["USER"] = $_POST["username"];
			// redirect him
			header("Location: $thisscript");
			exit;
		}
		else {
			// Invalid (or first time) user. Show form (again).
			renderForm();
			exit;
		}
	}
	else {
		// Session is registered => User is logged in
		if ($action == "logout") {
			// On logout, unregister and redirect
			session_unregister("USER");
			header("Location: $thisscript");
			exit;
		}
		else {
			// Retrieve his username
			$username = $_SESSION["USER"];
		}
	}
}

// Cookie based authentication
else if ($authmethod == "cookie") {
	if (!isset($_COOKIE["USER"])) {
		if ( isset($_POST["username"])
					&& isset($_POST["password"])
					&& ($username == $_POST["username"])
					&& ($password == $_POST["password"])
				) {
				// Valid user, set the cookie and redirect
			setcookie("USER", $_POST["username"]);  
			header("Location: $thisscript");
			exit;
		}
		else {
			// show the form (again)
			renderForm();
			exit;
		}
	}
	else {
		// Cookie is already set
		if ($action == "logout") {
			// Delete the cookie and redirect
			setcookie("USER", false);  
			header("Location: $thisscript");
			exit;
		}
		else {
			// Retrieve username
			$username = $_COOKIE["USER"];
		}
	}
}

// HTTP authentication
else if ( $authmethod == "http" ) {
	if ( !isset($_SERVER["PHP_AUTH_USER"])
				|| ( $username != $_SERVER["PHP_AUTH_USER"] )
				|| ( $password != $_SERVER["PHP_AUTH_PW"] ) 
			) {
			// Not a valid user. Send headers
		header("WWW-Authenticate: Basic realm=\"Compress URL Authentication\"");
		header("HTTP/1.0 401 Unauthorized");
		echo "<center><div style='width:70%; background:#FFEBE8; padding:5px; margin:50px; text-align:center; font-weight:bold; 
					border: solid 1px #DD3C10; '>
						Authentication failed. Refresh to try again.
					</div></center>";
		exit;
		// No logout link. User just needs to close the browser window to close session
	}
	else {
		// Retrieve username
		$username = $_SERVER["PHP_AUTH_USER"];
	}
}
// End of authentication types

// Show logout link for session and cookie based auth
if ( ( $authmethod == "session" ) || ( $authmethod == "cookie" ) ) {
	echo "<a style='float:right; font-weight: bold' href='$thisscript?action=logout'> Logout $username</a>";
}
?>